package lambda;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;

// 自定义函数式接口
@FunctionalInterface
interface MathOperation {
    int operate(int a, int b);
}

public class LambdaScenarios {
    public static void main(String[] args) {
        // 1. 作为参数传递
        MathOperation addition = (a, b) -> a + b;
        MathOperation multiplication = (a, b) -> a * b;

        System.out.println("3 + 5 = " + calculate(3, 5, addition));
        System.out.println("3 * 5 = " + calculate(3, 5, multiplication));

        // 2. 集合排序
        List<String> fruits = Arrays.asList("Apple", "Banana", "Cherry", "Date");

        // 传统排序方式
        fruits.sort(new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.length() - s2.length();
            }
        });

        // Lambda排序方式
        fruits.sort((s1, s2) -> s1.length() - s2.length());
        System.out.println("\n按长度排序：" + fruits);

        // 3. 过滤操作
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        // 使用Predicate函数式接口
        System.out.println("\n偶数：");
        filter(numbers, n -> n % 2 == 0);

        System.out.println("大于5的数：");
        filter(numbers, n -> n > 5);
    }

    private static int calculate(int a, int b, MathOperation operation) {
        return operation.operate(a, b);
    }

    private static void filter(List<Integer> list, Predicate<Integer> predicate) {
        for (Integer n : list) {
            if (predicate.test(n)) {
                System.out.println(n);
            }
        }
    }
}
